package es.udc.iagolast.androidJam.Util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

@SuppressWarnings("rawtypes")
public class MyItemizedOverlay extends ItemizedOverlay {
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private Context mContext;

	/**
	 * Creates a new HelloItemizedOverlay Instance
	 * 
	 * @param defaultMarker
	 * @param context
	 *            context from de calling mapActivity
	 */
	public MyItemizedOverlay(Drawable defaultMarker, Context context) {
		super(boundCenterBottom(defaultMarker));
		mContext = context;
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	@Override
	protected OverlayItem createItem(int i) {
		return mOverlays.get(i);
	}

	public void addOverlay(OverlayItem overlay) {
		mOverlays.add(overlay);
		populate();
	}

	public void updateOverlay(OverlayItem overlay) {
		if (mOverlays.size() > 0) {
			mOverlays.set(mOverlays.size() - 1, overlay);
		} else {
			mOverlays.add(overlay);
		}
		populate();
	}

	public void update() {
		populate();
	}

	@Override
	protected boolean onTap(int index) {
		if (!mOverlays.isEmpty()) {
			OverlayItem item = mOverlays.get(index);
			AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			dialog.setTitle(item.getTitle());
			dialog.setMessage(item.getSnippet());
			dialog.show();
			return true;
		} else
			return true;
	}

	public void removeLast() {
		if (!mOverlays.isEmpty())
			mOverlays.remove(mOverlays.size() - 1);
		populate();
	}

	public OverlayItem getLastPosition() {
		return mOverlays.get((mOverlays.size() - 1));

	}

	public void loadFromFile(FileInputStream fIn) {
		ArrayList<OverlayItem> overlays = new ArrayList<OverlayItem>();

		try {
			InputStreamReader isr = new InputStreamReader(fIn);
			BufferedReader bff = new BufferedReader(isr);

			// Lectura del fichero
			String line;
			while ((line = bff.readLine()) != null) {
				// TODO: Crear un Overlay a partir de un String
				overlays.add(null);
			}

			// Cerramos el fichero
			fIn.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		this.mOverlays = overlays;
	}

	public void saveToFile(FileOutputStream fOut) {
		String line = new String();
		try {
			// Open an output stream
			PrintStream osw = new PrintStream(fOut);
			for (OverlayItem item : this.mOverlays) {
				line = item.getPoint().toString() + "#"
						+ item.getSnippet().toString();
				osw.println(line);
			}
		}
		// Catches any error conditions
		catch (Exception e) {
			System.err.println("Unable to write to file");
			System.exit(-1);
		}
	}
}
